/**
 * @name TodoList
 * @desc 待办事项
 * @author darcrand
 * @version 2018-10-04
 *
 * @prop {String} title - 显示在顶部的标题
 * @prop {Array} list - 待办事项列表
 * @prop {Number} list[].id - 待办项的唯一标识,实际是一个时间戳
 * @prop {String} list[].message - 待办项的内容
 * @prop {Boolean} list[].status - 表示待办项是否已经完成
 * @prop {Function} onListUpdate - 当待办项更新时执行的函数
 */

import React, { Component } from "react"
import AddTodo from "./AddTodo"
import TodoItem from "./TodoItem"
import TodoFilter from "./TodoFilter"
import "./styles.css"

class TodoList extends Component {
    static defaultProps = {
        title: "Todo List",
        list: [{ id: 0, message: "", status: false }],
        onListUpdate: newList => {}
    }

    state = {
        type: "ALL"
    }

    handleAddTodoItem = obj => {
        console.log("add", obj)
        const newList = [...this.props.list, obj]
        this.props.onListUpdate(newList)
    }

    handleToggleTodoStatus = id => {
        const newList = this.props.list.map(v => (v.id === id ? { ...v, status: !v.status } : v))
        this.props.onListUpdate(newList)
    }

    handleRemoveTodoItem = id => {
        this.props.onListUpdate(this.props.list.filter(v => v.id !== id))
    }

    handleUpdateFilter = type => {
        this.setState({ type })
    }

    render() {
        const showingList = this.props.list.filter(
            v => this.state.type === "ALL" || (this.state.type === "UNDO" && !v.status) || (this.state.type === "DONE" && v.status)
        )

        return (
            <div className="todo-list-container">
                <h2 className="todo-list-title">{this.props.title}</h2>

                <AddTodo handleAddTodoItem={this.handleAddTodoItem} />
                <TodoFilter type={this.state.type} handleUpdateFilter={this.handleUpdateFilter} />

                {showingList.map((v, i) => (
                    <TodoItem
                        key={v.id}
                        index={i}
                        data={v}
                        handleToggleTodoStatus={this.handleToggleTodoStatus}
                        handleRemoveTodoItem={this.handleRemoveTodoItem}
                    />
                ))}
            </div>
        )
    }
}

export default TodoList
